package main

import "fmt"

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

type ListNode struct {
	Val  int
	Next *ListNode
}

func printLine(head *ListNode) {
	for head != nil {
		fmt.Print(head.Val)
		head = head.Next
	}
	fmt.Println()
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	l1Head, flag := &ListNode{}, 0
	l1Cur := l1Head
	for l1 != nil || l2 != nil || flag == 1 {
		if l1 != nil {
			flag, l1 = flag+l1.Val, l1.Next
		}
		if l2 != nil {
			flag, l2 = flag+l2.Val, l2.Next
		}
		l1Cur.Next = &ListNode{Val: flag % 10}
		flag, l1Cur = flag/10, l1Cur.Next
	}
	return l1Head.Next
}

func createLine(valList []int) *ListNode {
	head := &ListNode{}
	cur := head
	for _, val := range valList {
		cur.Next = &ListNode{Val: val}
		cur = cur.Next
	}
	return head.Next
}

func main() {
	ln := addTwoNumbers(createLine([]int{9, 9, 9, 9, 9, 9, 9}), createLine([]int{9, 9, 9, 9}))
	for ln != nil {
		fmt.Print(ln.Val, " ")
		ln = ln.Next
	}
	fmt.Println()
}
